package com.test.platform.service.developer;

import com.fasterxml.jackson.databind.JsonNode;
import com.test.platform.dao.DeveloperInfoMapper;
import com.test.platform.model.DeveloperInfo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class DeveloperDataProcessor {
    private static final Logger logger = LoggerFactory.getLogger(DeveloperDataProcessor.class);

    @Autowired
    private DeveloperInfoMapper developerInfoMapper;

    @Autowired
    private RedissonClient redissonClient;


    public void processPRInfo(String owner, String name, JsonNode prNode) {
        String lockKey = "developer_info_lock:" + owner + ":" + name;
        RLock lock = redissonClient.getLock(lockKey);
        
        try {
            if (!lock.tryLock(5, 10, TimeUnit.SECONDS)) {
                logger.warn("无法获取分布式锁，跳过更新: {}/{}", owner, name);
                return;
            }

            String developer = prNode.path("user").path("name").asText();
            String prUrl = prNode.path("html_url").asText();
            String title = prNode.path("title").asText();
            
            if (developer.isEmpty() || prUrl.isEmpty() || title.isEmpty()) {
                logger.warn("PR信息不完整: developer={}, url={}, title={}", developer, prUrl, title);
                return;
            }
            
            int prNumber = extractPRNumber(prUrl);
            updateDeveloperInfo(owner, name, developer, prNumber, title);
            
        } catch (Exception e) {
            logger.error("处理PR信息时发生错误: {}/{}", owner, name, e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    private int extractPRNumber(String prUrl) {
        try {
            return Integer.parseInt(prUrl.substring(prUrl.lastIndexOf('/') + 1));
        } catch (Exception e) {
            logger.error("解析PR编号失败: URL={}", prUrl, e);
            throw new RuntimeException("无法从URL提取PR编号: " + prUrl);
        }
    }

    private void updateDeveloperInfo(String owner, String name, String developer, int prNumber, String title) {
        try {
            var existingInfos = developerInfoMapper.findByOwnerAndName(owner, name);
            
            DeveloperInfo developerInfo = new DeveloperInfo();
            developerInfo.setOwner(owner);
            developerInfo.setName(name);
            developerInfo.setDeveloper(developer);
            developerInfo.setPullRequest(prNumber);
            developerInfo.setTitle(title);
            
            if (existingInfos != null && !existingInfos.isEmpty()) {
                developerInfo.setId(existingInfos.get(0).getId());
                developerInfoMapper.update(developerInfo);
            } else {
                developerInfoMapper.insert(developerInfo);
            }
            
            logger.info("开发者信息更新成功: {}/{} PR#{}", owner, name, prNumber);
        } catch (Exception e) {
            logger.error("更新开发者信息失败: {}/{}", owner, name, e);
            throw e;
        }
    }
}